package com.jch.dm2_guarded_suspension.demo_code;

import com.jch.dm2_guarded_suspension.reusable_code.Blocker;
import com.jch.dm2_guarded_suspension.reusable_code.ConditionVarBlocker;
import com.jch.dm2_guarded_suspension.reusable_code.GuardedAction;
import com.jch.dm2_guarded_suspension.reusable_code.Predicate;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;

public class AlarmAgent {

    private volatile boolean connectedToServer = false;

    private final Predicate agentConnected = new Predicate(){

        @Override
        public boolean evaluate() {
            return connectedToServer;
        }
    };

    private final Blocker blocker = new ConditionVarBlocker();

    private final Timer heartbeatTimer = new Timer(true);

    public void sendAlarm(final String alarm) throws Exception {
        // 可能需要等待，直至AlarmAgent连接到告警服务器（或连接中断后重新连接上）
        GuardedAction<Void> guardedAction = new GuardedAction<Void>(agentConnected) {
            @Override
            public Void call() throws Exception {
                doSendAlarm(alarm);
                return null;
            }
        };
        blocker.callWithGuard(guardedAction);
    }

    private void doSendAlarm(String alarm) {
        System.out.println("sending alarm: " + alarm);
        try {
            Thread.sleep(50); // 模拟发送耗时
        } catch (InterruptedException e) {
        }
    }

    public void init(){
        // 告警连接线程
        Thread connectingThread = new Thread(new ConnectingTask());
        connectingThread.start();
        heartbeatTimer.schedule(new HeartbeatTask(),60000,2000);
    }

    public void disconnect(){
        System.out.println("disconnected from alarm server.");
        connectedToServer = false;
    }

    public void onConnected(){
        try {
            blocker.signalAfter(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    connectedToServer = true;
                    System.out.println("connected to server.");
                    return Boolean.TRUE;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void onDisconnected(){
        connectedToServer = false;
    }

    private class ConnectingTask implements Runnable {
        @Override
        public void run() {
            // 模拟 负责与告警服务器建立网络连接
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            onConnected();
        }
    }

    private class HeartbeatTask extends TimerTask {
        @Override
        public void run() {
            // 模拟 心跳任务，定时检查与告警服务器的连接是否正常，发现异常后自动重新连接
            if (!testConnection()){
                onConnected();
                reconnect();
            }
        }

        private boolean testConnection() {
            // 模拟 测试连接
            return true;
        }

        private void reconnect(){
            ConnectingTask connectingTask = new ConnectingTask();
            connectingTask.run();
        }
    }

    public static void main(String[] args) throws Exception {
        AlarmAgent alarmAgent = new AlarmAgent();
        alarmAgent.init();
        alarmAgent.sendAlarm("test test");
    }
}
